//
//  RHLocalParamSetListVC.m
//  RuiHeAppApp
//
//  Created by Yan Chen on 2024/4/9.
//

#import "RHLocalParamSetListVC.h"
#import "RHDevParaModel.h"
#import "LocalChoiceEndpointVC.h"
#import "RHLocalChartHeaderView.h"
#import "RHLocalSettingCell.h"
#import "RHLocalChoiceParaView.h"
#import "WSDatePickerView.h"
#import "CBLECenterMnger.h"
#import "RHBleCmdData.h"
#import "CBLEDataParse.h"
#import "RHCustomTimer.h"
#import "JCDataConvert.h"
#import "SYChartTool.h"

#define TIMEOUT 5 //命令超时响应
@interface RHLocalParamSetListVC ()<UITableViewDataSource,UITableViewDelegate>
@property (nonatomic ,strong) UITableView *tableView;

//参数
@property (nonatomic,strong) NSMutableArray *paraArray;

@property (nonatomic ,strong) RHLocalChartHeaderView *headerView;

@property (nonatomic ,strong) RHLocalEndpointModel *curModel;

@property (nonatomic ,strong) NSMutableArray *endPointArr;

@property (nonatomic,strong) RHLocalSettingTypeModel *settingTypeModel;

@property (nonatomic ,assign) NSInteger cmdIndex;

//保存设备读到的值
@property (nonatomic ,strong) NSMutableDictionary *devInfo;

//发送命令后没有回复超时定时器
@property (nonatomic ,strong) NSTimer *cmdTimeOutTimer;

@property (nonatomic ,assign) NSInteger timeCount;
//发送读指令还是写指令
@property (nonatomic ,copy) void (^cmdBlock)(void);

@property (nonatomic, strong) MBProgressHUD *hud;
//停止继续发送命令
@property (nonatomic ,assign) BOOL stopSendCmd;
//sn和版本模型
@property (nonatomic ,strong) NSArray *snCmdArr;
//pack的数量
@property (nonatomic, assign) NSInteger packCount;
//当前pack选择的下标,暂时没用,已在选择pack列表时作了处理
@property (nonatomic, assign) NSInteger packCmdIndex;

//pack  sn
@property (nonatomic, strong) NSArray *packSnArr;
//循环读取pack sn 的下标
@property (nonatomic, assign) NSInteger packReadIndex;
//是否读取完sn
@property (nonatomic, assign) BOOL hasReadPackSN;
@end

@implementation RHLocalParamSetListVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = CFTabViewBgColor;
    self.paraArray = [NSMutableArray array];
    self.endPointArr = [NSMutableArray array];
    self.settingTypeModel = [RHLocalSettingTypeModel getTypeModelWithSettingType:self.settingType];
    self.settingTypeModel.endPointCode = [self.settingTypeModel getEndpointCode];
    
    //高低压判断
    if ([CBLECenterMnger shareMnger].curPheral.isHighVoltage == NO) {
        NSMutableArray *mtbArr = [NSMutableArray arrayWithArray:self.settingTypeModel.dataList];
        NSMutableArray *deleteArr = [NSMutableArray array];
        [mtbArr enumerateObjectsUsingBlock:^(RHLocalSettingModel*  _Nonnull model, NSUInteger idx, BOOL * _Nonnull stop) {
              //去除json文件中高压部分参数
            if([model.field isEqualToString:@"M_HighSystemSet1"]||[model.field isEqualToString:@"M_HighSystemSet2"]){
                [deleteArr addObject:model];
            }
        }];
        [mtbArr removeObjectsInArray:deleteArr];
        self.settingTypeModel.dataList = mtbArr.copy;
    }
    
    //沛城16度电的没有参数设置,只保留上面的sn
    if ([CBLECenterMnger shareMnger].curPheral.productId == 300 && [self.settingTypeModel.endPointCode isEqualToString:@"Pack"]) {
        self.settingTypeModel.dataList = @[];
    }
    
    [self setupUI];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        //构建 sn 和 软硬件版本信息命令
        [self buildSnAdnVersionCommand];
        if ([self.settingTypeModel.endPointCode isEqualToString:@"Pack"]) {
            //有的设备是没有主控的,这里默认给8,循环读取sn,能读取的就添加
            self.packCount = 8;
            //如果是pack模块,读到其他不存的pack会弹设备不在线,这里不弹提示
            [ProgressHUDManage shareObject].showErrorTips = NO;
            //pack模块读取总个数
//            [self getDevicePackCount];
            //循环读取每个pack的sn
            if (self.hasReadPackSN == NO) {
                self.packReadIndex = 0;
                [self loopReadPackSn];
            }
        }else{
            //其他模块正常读取参数列表
            [self readDeviceInfoFromBle];
        }
 
    });
    
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [ProgressHUDManage shareObject].showErrorTips = YES;
}

#pragma mark --------------- 1. SN 和 版本 命令------------------
-(void)buildSnAdnVersionCommand
{
    self.curModel = [[RHLocalEndpointModel alloc]init];
    
    NSArray *infoArr = [SYChartTool loadJsonFileWithName:@"setting_sn_version"];
    NSMutableArray *mtbArr = [NSMutableArray array];
    [infoArr enumerateObjectsUsingBlock:^(NSArray  *_Nonnull arr, NSUInteger idx, BOOL * _Nonnull stop) {
        NSArray *modelArr = [NSArray yy_modelArrayWithClass:[RHLocalSettingModel class] json:arr];
        [mtbArr addObject:modelArr];
    }];
    
    NSInteger typeIndex = 0;
    //ems
    if(self.settingType == LocalSettingType_EMS){
        typeIndex = 0;
    }
    //master
    if(self.settingType == LocalSettingType_Master){
        typeIndex = 1;
    }
    //pack  分了pack1 - pack6
    if([self.settingTypeModel.endPointCode isEqualToString:@"Pack"]){
        typeIndex = 2;
    }
    //sn和软件版本命令
    self.snCmdArr = mtbArr[typeIndex];
    
}

#pragma mark ------ 2.获取pack数量 (pack需要)  有的设备是不带主控的,所以改为默认8个pack,循环读取,有就添加
//-(void)getDevicePackCount
//{
//    self.packCmdIndex = 0;
//    NSDictionary *dic = @{
//        @"field":@"Mtr_PackCnt",
//        @"regAddr":@(4012),
//        @"bitWidth":@(16),
//        @"cmdType":@(LocalSettingType_Master)
//    };
//
//    RHLocalSettingModel *settingModel = [RHLocalSettingModel yy_modelWithJSON:dic];
//    NSData *data =  [RHBleCmdData buildSingleReadCmdWithSettingModel:settingModel settingType:self.settingTypeModel.settingType];
//    [[CBLECenterMnger shareMnger] wristReadData:data];
//}

#pragma mark ------- 3.循环读取pack sn
-(void)loopReadPackSn
{
    if (self.packReadIndex == self.packCount) {
        self.curModel = [self.endPointArr firstObject];
        self.headerView.endPointModel = self.curModel;
        self.hasReadPackSN = YES;
        //读完pack的所有sn,接着读参数
        [self readDeviceInfoFromBle];
        return;
    }
    RHLocalSettingModel *snModel = [self.snCmdArr firstObject];//第一个是sn命令
    NSLog(@"---->读取第%ld个 pack sn 指令:%@",self.packReadIndex+1,snModel.field);
    self.hud.label.text = [NSString stringWithFormat:@"%@(%ld/%ld)",@"读取数据".rh_localized,self.packReadIndex+1,self.packCount];
    NSData *data =  [RHBleCmdData buildSingleReadCmdWithSettingModel:snModel settingType:self.settingTypeModel.settingType+self.packReadIndex];
    [[CBLECenterMnger shareMnger] wristReadData:data];
    
}

#pragma mark ---------------4. 读取设备列表信息 (参数 , sn , 版本信息)------------------
-(void)readDeviceInfoFromBle
{
    
    self.stopSendCmd = NO;
    self.cmdIndex = 0;
    NSMutableArray *mtbArr = [NSMutableArray array];
    self.devInfo = [NSMutableDictionary dictionary];
    //加入sn和版本命令
    [mtbArr addObjectsFromArray:self.snCmdArr];
    //列表
    [self showHud];
    [self.settingTypeModel.dataList enumerateObjectsUsingBlock:^(RHLocalSettingModel  *_Nonnull settingModel, NSUInteger idx, BOOL * _Nonnull stop) {

            [settingModel.properList enumerateObjectsUsingBlock:^(RHLocalSettingModel * _Nonnull obj, NSUInteger index, BOOL * _Nonnull stop) {
                //master,pack的时间校准不读取,读取不到,只设置   Pck_ctrlTimyear
                if(obj.isWriteOnly){
                    return;
                }
                [mtbArr addObject:obj];
                    
            }];
    }];
    self.cmdArray = mtbArr.copy;
    
    kWeakSelf;
    self.cmdBlock = ^{
        [weakSelf sendReadCmd];
    };
    self.cmdBlock();
}

#pragma mark ------发送读取指令   如果是pack模块,得加上对应索引
-(void)sendReadCmd
{
    if(self.stopSendCmd){
        return;
    };
    RHLocalSettingModel *settingModel = self.cmdArray[self.cmdIndex];
    NSLog(@"---->发送第%ld条读取指令:%@",self.cmdIndex,settingModel.field);
    self.hud.label.text = [NSString stringWithFormat:@"%@(%ld/%ld)",@"读取数据".rh_localized,self.cmdIndex+1,self.cmdArray.count];
    NSData *data =  [RHBleCmdData buildSingleReadCmdWithSettingModel:settingModel settingType:self.settingTypeModel.settingType];
    [[CBLECenterMnger shareMnger] wristReadData:data];
    //开始计时,5秒内没收到应答就继续发送下一条指令
    [self timeOutAction];
}

#pragma mark ------发送写指令
-(void)sendWriteCmd
{
    if(self.stopSendCmd){
        return;
    };
    if(self.cmdArray.count == 0){
        [self.hud hideAnimated:YES];
        [MBProgressHUD dismiss];
        return;
    }
    RHLocalSettingModel *settingModel = self.cmdArray[self.cmdIndex];
    NSLog(@"---->发送第%ld条设置指令:%@",self.cmdIndex+1,settingModel.field);
    self.hud.label.text = [NSString stringWithFormat:@"%@(%ld/%ld)",@"设置参数".rh_localized,self.cmdIndex+1,self.cmdArray.count];
    NSData *data =  [RHBleCmdData buildSingleSetCmdWithSettingModel:settingModel settingType:self.settingTypeModel.settingType];
    [[CBLECenterMnger shareMnger] wristWriteData:data];
    //开始计时,5秒内没收到应答就继续发送下一条指令
    [self timeOutAction];
}

-(void)timeOutAction
{
    [self.cmdTimeOutTimer invalidate];
    self.cmdTimeOutTimer = nil;
    self.timeCount = 0;
    self.cmdTimeOutTimer = [RHCustomTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeCounting) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.cmdTimeOutTimer forMode:NSRunLoopCommonModes];
}

-(void)timeCounting
{
    if(self.timeCount >= TIMEOUT){
        //发送下一条指令
        self.cmdIndex ++;
        if(self.cmdIndex >= self.cmdArray.count){
            [self.hud hideAnimated:YES];
            [MBProgressHUD dismiss];
            [self.cmdTimeOutTimer invalidate];
            self.cmdTimeOutTimer = nil;
            return;
        }
        self.cmdBlock();
        return;
    }
    self.timeCount++;
    NSLog(@"---->计时:%ld",self.timeCount);
}

#pragma mark --------------- 收到设备信息 ---------------
-(void)receiveDeviceMsg:(NSNotification*)no
{
    
    NSDictionary *dic = [no object];
    if(dic.allKeys.count==0)return;
    if (self.recieveMsg == NO) return;
    //消息的端点类型
    LocalSettingType cmdType = [RHBleCmdData toSettingType:[dic[CMD_TYPE] integerValue]];
    NSLog(@"------当前端点类型:%ld  返回命令类型:%ld",self.settingType,cmdType);
    
    //如果是pack里读取模块数量(用的master里的命令) , 有的设备是不带主控的,所以为了兼容,不去读主控里pack的数量,改为默认6,循环读取添加
//    if(([dic[CMD_ADDRESS] integerValue] == 4012)&& (!self.hasReadPackSN) && [self.settingTypeModel.endPointCode isEqualToString:@"Pack"]){
//        NSData *data = dic[CMD_ADDRESS_VALUE];
//        self.packCount = [JCDataConvert dataToInt:data];
//        if (self.packCount == 0) {
//            self.packCount = 1;
//        }
//        NSLog(@"------->pack模块数量:%ld",self.packCount)
//        //循环读取每个pack的sn
//        if (self.hasReadPackSN == NO) {
//            self.packReadIndex = 0;
//            [self loopReadPackSn];
//        }
//        return;
//    }
    
    //  循环读取所有pack sn
    if(([dic[CMD_ADDRESS] integerValue] == 4200)&& (!self.hasReadPackSN) && [self.settingTypeModel.endPointCode isEqualToString:@"Pack"]){
        __block BOOL isExit = NO;
        NSData *data = dic[CMD_ADDRESS_VALUE];
        RHLocalSettingModel *snModel = [self.snCmdArr firstObject];
        NSString *parse_content = [CBLEDataParse parseData:data settingModel:snModel];
        //循环读取每个pack的sn
        [self.endPointArr enumerateObjectsUsingBlock:^(RHLocalEndpointModel*  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
           
            if ([obj.sn isEqualToString:parse_content]) {
                isExit = YES;
            }
        }];
        //sn为空不添加
        if (parse_content.length == 0) {
            isExit = YES;
        }
        if (isExit == NO) {
            RHLocalEndpointModel *model = [[RHLocalEndpointModel alloc]init];
            model.sn = parse_content;
            model.endpointId = self.packReadIndex;
            model.endpointCode = self.settingTypeModel.endPointCode;
            [self.endPointArr addObject:model];
        }
        self.packReadIndex ++;
        [self loopReadPackSn];
        return;
    }
 //-------------------在没有读取完pack 数量以及各个pack的sn时,先不做其他操作 -----------------------
    //返回的数据如果不是当前端点类型的过滤掉  pack除外
    if(cmdType != self.settingType){
        return;
    }
    
    //消息是读还是写回复
    int answerType = [dic[CMD_CODE] intValue];
    if(answerType == 0x03){
        //读回复
        [self deviceAnswerReadCmd:dic];
    }
    
    if(answerType == 0x10){
        //写回复
        [self deviceAnswerWriteCmd:dic];
    }
    
    if(answerType == 0x90){
        //设置失败
        [self.hud hideAnimated:YES];
        [QMUITips hideAllTips];
    }
    
}


-(void)deviceAnswerReadCmd:(NSDictionary*)dic
{
    NSLog(@"---->self.index = %ld, self.cmdArray.count = %ld",self.cmdIndex,self.cmdArray.count);
    NSLog(@"------>收到设备信息:%@",dic);
    
    NSData *data = dic[CMD_ADDRESS_VALUE];
    if(data.length >= 0){
        int result = [JCDataConvert dataToInt:data];
        //模块失联
        if(result == 0x06){
            
        }
    }
    
    [self.settingTypeModel.dataList enumerateObjectsUsingBlock:^(RHLocalSettingModel  *_Nonnull settingModel, NSUInteger idx, BOOL * _Nonnull stop) {
        if([settingModel.type isEqualToString:@"command"]){
            return;
        }

            [settingModel.properList enumerateObjectsUsingBlock:^(RHLocalSettingModel * _Nonnull obj, NSUInteger index, BOOL * _Nonnull stop) {
                if(obj.regAddr == [dic[CMD_ADDRESS] integerValue]){
                    NSData *data = dic[CMD_ADDRESS_VALUE];
                    NSString *parse_content = [CBLEDataParse parseData:data settingModel:obj];
                    NSLog(@"---->%@ = %@",obj.field,parse_content);
                    obj.content = parse_content;
                   
                   
                    [self.devInfo setObject:obj.content?obj.content:@"" forKey:obj.field];
                }
                   
            }];

        
    }];
    
    
    kWeakSelf;
    //判断是否收到sn和版本信息
    [self.snCmdArr enumerateObjectsUsingBlock:^(RHLocalSettingModel  *_Nonnull model, NSUInteger idx, BOOL * _Nonnull stop) {
        if(model.regAddr == [dic[CMD_ADDRESS] integerValue]){
            NSLog(@"读取到版本信息:%@ = %@",model.field,dic[CMD_ADDRESS_VALUE]);
            NSData *data = dic[CMD_ADDRESS_VALUE];
            NSString *parse_content = [CBLEDataParse parseData:data settingModel:model];
            if([model.comment containsString:@"SN"]){
                self.curModel.sn = parse_content;
            }
            if([model.comment containsString:@"SoftWare"]){
                NSInteger ver_h = [parse_content integerValue] >> 8;
                NSInteger ver_l = [parse_content integerValue] & 0xff;
                self.curModel.lastVersion = [NSString stringWithFormat:@"%ld:%03ld",ver_h,ver_l];
            }
            if([model.comment containsString:@"HardWare"]){
                NSInteger ver_h = [parse_content integerValue] >> 8;
                NSInteger ver_l = [parse_content integerValue] & 0xff;
                self.curModel.hardVersion = [NSString stringWithFormat:@"%ld:%03ld",ver_h,ver_l];
            }
            self.curModel.endpointCode = [self.settingTypeModel getEndpointCode];
            self.headerView.endPointModel = self.curModel;
        }
    }];
    
    //发送下一条读数据
    if(self.cmdIndex < self.cmdArray.count-1){
        NSLog(@"---->读取下一条数据:%ld",self.cmdIndex+1);
        self.cmdIndex ++ ;
        [self sendReadCmd];
    }else{
        NSLog(@"----读取完毕  self.type == %ld",self.settingType);
        [self.hud hideAnimated:YES];
        [self.tableView endHeaderRefresh];
        [self.cmdTimeOutTimer invalidate];
        self.cmdTimeOutTimer = nil;
    }
    
    [self.tableView reloadData];
}

-(void)deviceAnswerWriteCmd:(NSDictionary*)dic{
    NSData *data = dic[CMD_ADDRESS_VALUE];
    if(data.length >= 0){
        int result = [JCDataConvert dataToInt:data];
        //写成功
        if(result == 0x00){
            //更新原来的旧值
           NSInteger addr = [dic[CMD_ADDRESS]integerValue];
            [self.settingTypeModel.dataList enumerateObjectsUsingBlock:^(RHLocalSettingModel  *_Nonnull sectionModel, NSUInteger idx, BOOL * _Nonnull stop) {
                [sectionModel.properList enumerateObjectsUsingBlock:^(RHLocalSettingModel * _Nonnull settingModel, NSUInteger idx, BOOL * _Nonnull stop) {
                    if(settingModel.regAddr == addr){
                        if(settingModel.isBit){
                            [self.devInfo setObject:@(settingModel.originalValue) forKey:settingModel.field];
                            NSLog(@"---->设置成功后  devinfo = %ld",settingModel.originalValue);
                        }
                        //字符串,整形,不是位枚举的选择菜单
                        [self.devInfo setObject:settingModel.content forKey:settingModel.field];
                        
                        
                    }
                }];
            }];
            if(self.cmdIndex == self.cmdArray.count - 1){
                [MBProgressHUD showSuccess:@"设置成功".rh_localized];
            }
        }else{
            
        }
    }
    
    //发送下一条设置指令
    if(self.cmdIndex < self.cmdArray.count-1){
        NSLog(@"----设置下一条指令:%ld",self.cmdIndex+1);
        self.cmdIndex ++ ;
        [self sendWriteCmd];
    }else{
        NSLog(@"----设置完毕  self.type == %ld",self.settingType);
        [self.hud hideAnimated:YES];
        [self.tableView endHeaderRefresh];
        [self.cmdTimeOutTimer invalidate];
        self.cmdTimeOutTimer = nil;
    }
    
}


#pragma mark ------ 修改参数 -------
-(void)setParamterWithModel:(RHLocalSettingModel*)settingModel 
{
    self.stopSendCmd = NO;
    self.cmdIndex = 0;
    
    NSMutableArray *mtbArr = [NSMutableArray array];
    __block RHLocalSettingModel *lastModel;
    [settingModel.properList enumerateObjectsUsingBlock:^(RHLocalSettingModel * _Nonnull obj, NSUInteger index, BOOL * _Nonnull stop) {
        if (obj.isReadOnly) return;
        
        //设置的值和原来的值不一样并且有值才下发
        if(obj.isBit){
            //如果和上一个参数的寄存器地址一样就不添加,位数据只发送一次就可以了
            if(lastModel){
                if(obj.regAddr == lastModel.regAddr){
                    return;
                }else{
                    //如果不一样,则是另一个位参数
                    if(![obj.content isEqualToString:self.devInfo[obj.field]]){
                        [mtbArr addObject:obj];
                        lastModel = obj;
                    }
                }
                    
            }else{
                if(![obj.content isEqualToString:self.devInfo[obj.field]]){
                    [mtbArr addObject:obj];
                    lastModel = obj;
                }
            }
            
        }else{
            if(![obj.content isEqualToString:self.devInfo[obj.field]] && obj.content.length>0){
                NSLog(@"----->加入%@",obj.field);
                [mtbArr addObject:obj];
            }
        }
        
    }];
    self.cmdArray = mtbArr.copy;
    if(self.cmdArray.count == 0){
        [QMUITips showInfo:@"没有可提交的参数".rh_localized];
        return;
    }
    [self showHud];
      
    kWeakSelf;
    self.cmdBlock = ^{
        [weakSelf sendWriteCmd];
    };
    
    [self sendWriteCmd];
}

#pragma mark ------ 读取参数 -------
-(void)readParamterWithModel:(RHLocalSettingModel*)settingModel
{
    self.stopSendCmd = NO;
    self.cmdIndex = 0;
    
    NSMutableArray *mtbArr = [NSMutableArray array];
    __block RHLocalSettingModel *lastModel;
    [settingModel.properList enumerateObjectsUsingBlock:^(RHLocalSettingModel * _Nonnull obj, NSUInteger index, BOOL * _Nonnull stop) {
        if(obj.isWriteOnly)return;//只写的不读,如系统时间校准 Pck_ctrlTimyear
        
        //设置的值和原来的值不一样并且有值才下发
        if(obj.isBit){
            //如果和上一个参数的寄存器地址一样就不添加,位数据只发送一次就可以了
            if(lastModel){
                if(obj.regAddr == lastModel.regAddr){
                    return;
                }else{
                    //如果不一样,则是另一个位参数
                    [mtbArr addObject:obj];
                    lastModel = obj;
                }
                    
            }else{
                [mtbArr addObject:obj];
                lastModel = obj;
            }
            
        }else{
            [mtbArr addObject:obj];
        }
        
    }];
    self.cmdArray = mtbArr.copy;
    if(self.cmdArray.count == 0){
        return;
    }
    [self showHud];
      
    kWeakSelf;
    self.cmdBlock = ^{
        [weakSelf sendReadCmd];
    };
    
    [self sendReadCmd];
}


#pragma mark ------- 选择时间 -----------------------
- (void)dateAction:(RHLocalSettingModel *)settingModel {
 
    WSDatePickerView *datePickerV = [[WSDatePickerView alloc] initWithDateStyle:DateStyleShowYearMonthDayHourMinuteSecond CompleteBlock:^(NSDate *selectDate) {
        NSString *dateFormatStr = @"yyyy/MM/dd HH:mm:ss";
        NSString *currentDate = [selectDate stringWithFormat: dateFormatStr];
        settingModel.content = currentDate;
        [self.tableView reloadData];
    }];
    datePickerV.dateLabelColor = FontColor(@"#3ECE80");//年-月 颜色
    datePickerV.datePickerColor = UIColorBlack;//滚轮日期颜色
    datePickerV.doneButtonColor = UIColor.blackColor;//确定按钮的颜色
    [datePickerV show];
}

#pragma mark ------- 指令设置 ------
-(void)commandAction:(RHLocalSettingModel *)settingModel
{
    //指令用MB,和其他的分开控制
//    [MBProgressHUD showDefaultLoadingMessage:@""];
//    
//    NSData *data =  [RHBleCmdData buildSingleSetCmdWithSettingModel:settingModel settingType:self.settingTypeModel.settingType];
//    [[CBLECenterMnger shareMnger] wristWriteData:data];
//    self.stopSendCmd = YES;
    
    self.stopSendCmd = NO;
    self.cmdIndex = 0;
    self.cmdArray = @[settingModel];
  
      
    kWeakSelf;
    self.cmdBlock = ^{
        [weakSelf sendWriteCmd];
    };
    
    [self sendWriteCmd];
}


//选择枚举项
-(void)selectAction:(RHLocalSettingModel*)setttingModel
{
    kWeakSelf;
    RHLocalChoiceParaView *paraView = [[RHLocalChoiceParaView alloc]init];
    paraView.curParaModel = setttingModel;
    paraView.choiceResultBlock = ^(RHLocalSettingModel * _Nonnull model) {
        
        
        //如果是位的话,操作一个会影响的位,这里要同步更新一下其他的位值  还有开关项要处理
        if(model.isBit){
            model.originalValue = [weakSelf modifyByteWith:model.originalValue newValue:[model.content integerValue] bitWidth:model.bitWidth offset:model.offset];
            NSLog(@"---->选择了枚举项:%ld 选择后的值:%ld",[model.content integerValue],model.originalValue);
            //遍历所有组,以防其中的某一个位数据在其他的组,不过这样会费时
            [weakSelf.settingTypeModel.dataList enumerateObjectsUsingBlock:^(RHLocalSettingModel  *_Nonnull settingModel, NSUInteger idx, BOOL * _Nonnull stop) {
               
                    [settingModel.properList enumerateObjectsUsingBlock:^(RHLocalSettingModel * _Nonnull obj, NSUInteger index, BOOL * _Nonnull stop) {
                        //只处理和操作的枚举相同的寄存器
                        if(obj.regAddr == model.regAddr && ![obj.field isEqualToString:model.field]){
                            obj.originalValue = model.originalValue;
                           
                        }
                    
                    }];
            }];
        }
        [self.tableView reloadData];
    };
    [paraView showAnimation];
}


//开关枚举项
-(void)switchAction:(RHLocalSettingModel*)model

{
    
    
    
}




/// 修改字节中的某几位
/// - Parameters:
///   - value: 原来的值
///   - newValue: 要修改的值
///   - bitWidth: 位宽(要修改的位数)
///   - offset: 从哪一位开始修改
-(NSInteger)modifyByteWith:(uint16_t)value newValue:(int)newValue bitWidth:(int)bitWidth offset:(int)offset {
    
    int mask = [RHBleCmdData offsetValueWithBitWidth:bitWidth];
    
    // 清除目标位
    value &= ~(mask << offset); // 11111000
    
    // 将新值移到正确的位置
    newValue <<= offset; // 00001000
    
    // 将新值插入到字节中
    NSInteger finalValue =    value |= newValue; // 10101000
    
    /*----方法一
         unsigned char byte = 0x55; // 10101010
         unsigned char new_value = 2; // 0000010
      
         // 清除目标位
         byte &= ~(0x3 << 2); // 11111000
      
         // 将新值移到正确的位置
         new_value <<= 2; // 00001000
      
         // 将新值插入到字节中
         byte |= new_value; // 10101000
      
         printf("Modified byte: %x\n", byte);
      
         return 0;

     */
    
    
    /*-----方法二
        unsigned char byte = 0x55; // 10101010
        unsigned char new_value = 2; // 0000010
        int mask = 0x3; // 00000011
        int shift = 2; // 目标位数
     
        byte = (byte & ~(mask << shift)) | (new_value << shift);
     
        printf("Modified byte: %x\n", byte);
 */
    return finalValue;
}


-(void)setupUI
{
    ADD_MESSAGE(BLEMSG_PHERAL_SENDMSG_ACK, receiveDeviceMsg:);
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    [_tableView setBackgroundColor:CFTabViewBgColor];
    [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [_tableView registerClass:[RHLocalSettingCell class] forCellReuseIdentifier:LocalSettingAddSubCell];
    [_tableView registerClass:[RHLocalSettingCell class] forCellReuseIdentifier:LocalSettingTextInputCell];
    [_tableView registerClass:[RHLocalSettingCell class] forCellReuseIdentifier:LocalSettingSelectCell];
    [_tableView registerClass:[RHLocalSettingCell class] forCellReuseIdentifier:LocalSettingSwitchCell];
    [_tableView registerClass:[RHLocalSettingCell class] forCellReuseIdentifier:LocalSettingCommandCell];
    [_tableView registerClass:[RHLocalSettingCell class] forCellReuseIdentifier:LocalSettingDateCell];
    [_tableView setSeparatorColor:kRGB(240, 240, 240) ];
    _tableView.tableHeaderView = self.headerView;
    [_tableView setDelegate:self];
    [_tableView setDataSource:self];
    [self.view addSubview:_tableView];
    if (@available(iOS 11.0, *)) {
        _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    
    if (@available(iOS 15.0, *)) {
        _tableView.sectionHeaderTopPadding = 0;
    }
    
    kWeakSelf;
    [_tableView addHeaderRefresh:^{
        [weakSelf readDeviceInfoFromBle];
    }];
    
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(0);
        make.top.mas_offset(0);
        make.right.mas_offset(0);
        make.bottom.mas_offset(0);
    }];
}

- (UIView *)headerView{
    if(!_headerView){
        _headerView = [[RHLocalChartHeaderView alloc]init];
        _headerView.frame = CGRectMake(0, 0, kUI_WINDOW_W, kScaleW(45)*2+10);
//        if(self.endPointTypeModel.nodes.count>0){
//            _headerView.endPointModel = [self.endPointTypeModel.nodes firstObject];
//        }
        kWeakSelf;
        _headerView.selectBlock = ^{
            [UIView animateWithDuration:0.2 animations:^{
                weakSelf.headerView.arrowImg.transform = CGAffineTransformMakeRotation(M_PI/2);
            }];
            
            LocalChoiceEndpointVC *vc = [[LocalChoiceEndpointVC alloc]init];
            vc.endpointName = weakSelf.settingTypeModel.endPointCode;
            vc.endPointArr = weakSelf.endPointArr;
            vc.curModel = weakSelf.curModel;
            [[RHWindowTipManage shareWindowTipManage] showWithController:vc];
            [vc showAnimation];
            vc.choiceResultBlock = ^(RHLocalEndpointModel * _Nonnull model) {
                if (model) {
                    weakSelf.curModel = model;
                    weakSelf.headerView.endPointModel = model;
                    //如果是pack,切换后要修改 指令的设备地地址
                    [weakSelf changeCommandType];
                    [weakSelf readDeviceInfoFromBle];
                }
                [UIView animateWithDuration:0.2 animations:^{
                    weakSelf.headerView.arrowImg.transform = CGAffineTransformIdentity;
                }];
                
            };
        };
    }
    return _headerView;
}

#pragma mark ---------- 选择了子端点,修改指令设备地址(目前仅pack需要)
-(void)changeCommandType
{
    if ([self.settingTypeModel.endPointCode isEqualToString:@"Pack"]) {
        self.settingType = LocalSettingType_Pack1 + self.curModel.endpointId;//选择的序号,加上之后对应101, 102, 103, 104...
        self.settingTypeModel.settingType = self.settingType;
    }
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    
    return self.settingTypeModel.dataList.count;;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    RHLocalSettingModel *typeModel = self.settingTypeModel.dataList[section];
    return typeModel.properList.count;
    
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
  
    return  UITableViewAutomaticDimension;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
   
    return 55;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    RHLocalSettingModel *typeModel = self.settingTypeModel.dataList[section];
    if([typeModel.type isEqualToString:@"command"]){
        return 10;
    }
   
    return 60;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    RHLocalSettingModel *typeModel = self.settingTypeModel.dataList[section];
   
    CGFloat height = 60;
    if([typeModel.type isEqualToString:@"command"]){
        height = 10;
    }
    
    UIView *footView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kUI_WINDOW_W, height)];
    footView.backgroundColor = CFTabViewBgColor;
    
    UIView *cornerView = [[UIView alloc]initWithFrame:CGRectMake(15, 0, kUI_WINDOW_W-30, height)];
    cornerView.backgroundColor = [UIColor whiteColor];
    cornerView.layer.cornerRadius = 8;
    cornerView.layer.maskedCorners = kCALayerMinXMaxYCorner|kCALayerMaxXMaxYCorner;
    [footView addSubview:cornerView];
    
    if(![typeModel.type isEqualToString:@"command"]){
        QMUIButton *submitBtn = [[QMUIButton alloc]init];
        [submitBtn setTitle:@"提交".rh_localized forState:UIControlStateNormal];
        [submitBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [submitBtn.titleLabel setFont:kSYSTEMFONT(14)];
        submitBtn.backgroundColor = CMainColorGreen;
        submitBtn.layer.cornerRadius = 17;
        [cornerView addSubview:submitBtn];
        kWeakSelf;
        [[submitBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
            [weakSelf setParamterWithModel:typeModel];
        }];
       
        [submitBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(cornerView.mas_centerX).offset(-35);
            make.centerY.mas_offset(0);
            make.height.offset(kScaleW(35));
            make.width.offset(kScaleW(90));
        }];
        
        QMUIButton *readBtn = [[QMUIButton alloc]init];
        [readBtn setTitle:@"读取".rh_localized forState:UIControlStateNormal];
        [readBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [readBtn.titleLabel setFont:kSYSTEMFONT(14)];
        readBtn.backgroundColor = CMainColorGreen;
        readBtn.layer.cornerRadius = 17;
        [cornerView addSubview:readBtn];
        [[readBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
            [weakSelf readParamterWithModel:typeModel];
        }];
       
        [readBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(cornerView.mas_centerX).offset(35);
            make.centerY.mas_offset(0);
            make.height.offset(kScaleW(35));
            make.width.offset(kScaleW(90));
        }];
    }
    
    
    return footView;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    
    UIView *headView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kUI_WINDOW_W, 55)];
    headView.backgroundColor = CFTabViewBgColor;
    
    UIView *containView = [[UIView alloc]initWithFrame:CGRectMake(15, 10, headView.width-30, 45)];
    containView.backgroundColor = UIColor.whiteColor;
    containView.layer.cornerRadius = 8;
    containView.layer.maskedCorners = kCALayerMinXMinYCorner|kCALayerMaxXMinYCorner;
    [headView addSubview:containView];
    
    QMUILabel *titleLab = [[QMUILabel alloc]initWithFrame:CGRectMake(20, 12.5, 300, 20)];
    RHLocalSettingModel *typeModel = self.settingTypeModel.dataList[section];
    
    if([typeModel.type isEqualToString:@"command"]){
        titleLab.text = @"指令".rh_localized;
    }else{
        titleLab.text = typeModel.nickname.rh_localized;
    }
    
    
    titleLab.textColor = [UIColor colorWithHexString:@"3F4443" alpha:01];
    titleLab.font = [UIFont systemFontOfSize:15];
    
    UIView *line = [[UIImageView alloc]initWithFrame:CGRectMake(10, 45, kUI_WINDOW_W-20-20, 1)];
    line.backgroundColor = kCOLOR_HEX(@"EBEDF0");
    [containView addSubview:line];
    [containView addSubview:titleLab];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_offset(20);
            make.right.mas_offset(-20);
            make.bottom.mas_offset(-1);
            make.height.offset(1);
    }];
    return headView;
  
    
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    kWeakSelf;
    RHLocalSettingModel *typeModel = self.settingTypeModel.dataList[indexPath.section];
    RHLocalSettingModel *settingModel = typeModel.properList[indexPath.row];
    //指令
    if([settingModel.type isEqualToString:@"command"]){
        RHLocalSettingCell *cell = [tableView dequeueReusableCellWithIdentifier:LocalSettingCommandCell];
        cell.paraModel = settingModel;
        cell.commandBlock = ^{
            [weakSelf commandAction:settingModel];
        };
        return cell;
    }
   
    RHLocalSettingCell *settingCell;
    if([settingModel.type isEqualToString:@"select"]){//枚举
        settingCell = [tableView dequeueReusableCellWithIdentifier:LocalSettingSelectCell];
        settingCell.selectBlock = ^{
            [weakSelf selectAction:settingModel];
        };
    }
    //加减
    else if([settingModel.type isEqualToString:@"number"])
    {
        //如果是位数据,开关值变更后要同步其他的位(Pack簇地址)
        settingCell = [tableView dequeueReusableCellWithIdentifier:LocalSettingAddSubCell];
    }else if ([settingModel.type isEqualToString:@"switch"]){//开关
        settingCell = [tableView dequeueReusableCellWithIdentifier:LocalSettingSwitchCell];
       
    }else if([settingModel.type isEqualToString:@"text"]){//文本输入
        settingCell = [tableView dequeueReusableCellWithIdentifier:LocalSettingTextInputCell];
    }else if([settingModel.type isEqualToString:@"date"]){//时间
        settingCell = [tableView dequeueReusableCellWithIdentifier:LocalSettingDateCell];
        
        settingCell.dateBlock = ^{
            [weakSelf dateAction:settingModel];
        };
    }
    
    //位数据有开关,整形,下拉选择等类型,修改了其中一项,其他的要同步更新
    settingCell.bitValueChangBlock = ^(RHLocalSettingModel * model) {
        model.originalValue = [weakSelf modifyByteWith:model.originalValue newValue:[model.content integerValue] bitWidth:model.bitWidth offset:model.offset];
        //遍历所有组,以防其中的某一个位数据在其他的组,不过这样会费时
        [weakSelf.settingTypeModel.dataList enumerateObjectsUsingBlock:^(RHLocalSettingModel  *_Nonnull settingModel, NSUInteger idx, BOOL * _Nonnull stop) {
           
                [settingModel.properList enumerateObjectsUsingBlock:^(RHLocalSettingModel * _Nonnull obj, NSUInteger index, BOOL * _Nonnull stop) {
                    //只处理和操作的枚举相同的寄存器
                    if(obj.regAddr == model.regAddr && ![obj.field isEqualToString:model.field]){
                        obj.originalValue = model.originalValue;
                       
                    }
                
                }];
        }];
        
    };
    
    settingCell.paraModel = settingModel;
    settingCell.selectionStyle = UITableViewCellSelectionStyleNone;
    if(settingCell == nil) return [UITableViewCell new];
    return settingCell;
}

-(void)showHud{
    if (self.navigationController.view==nil) {
        return;
    }
    _hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
    _hud.mode = MBProgressHUDModeText;
    //不使用蒙版,使用背景颜色
    _hud.bezelView.style = MBProgressHUDBackgroundStyleSolidColor;
    _hud.bezelView.backgroundColor = kColorRGBA(0, 0, 0,  0.8);
    //图片和文字的颜色
    _hud.contentColor = [UIColor whiteColor];
    _hud.removeFromSuperViewOnHide = YES;
    _hud.label.text = [NSString stringWithFormat:@"%@(%ld/%ld)",@"读取数据".rh_localized,self.cmdIndex,self.cmdArray.count];
    // Configure the button.
    [_hud.button setTitle:@"取消".rh_localized forState:UIControlStateNormal];
    [_hud.button addTarget:self action:@selector(cancelWork:) forControlEvents:UIControlEventTouchUpInside];

}

-(void)cancelWork:(UIButton*)button
{
    self.stopSendCmd = YES;
    [self.cmdTimeOutTimer invalidate];
    self.cmdTimeOutTimer = nil;
    self.cmdIndex = 0;
    [self.hud hideAnimated:YES];
    [self.tableView endHeaderRefresh];
}

-(UIView *)listView
{
    return self.view;
}

-(void)dealloc
{
    [[RHBleCmdManager shareMnger]removeAllCommand];
    [self.hud hideAnimated:NO];
    [self.cmdTimeOutTimer invalidate];
    self.cmdTimeOutTimer = nil;
}

@end
